package com.sun.future;

import java.util.concurrent.*;

public class EcommerceOrderProcessingExample {

    private static final ExecutorService executor = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("开始处理订单...");
        long startTime = System.currentTimeMillis();

        String orderId = "ORDER-12345";

        // 并行执行多个任务
        CompletableFuture<String> userValidationFuture = validateUserAsync(orderId);
        CompletableFuture<String> inventoryCheckFuture = checkInventoryAsync(orderId);
        CompletableFuture<String> paymentProcessingFuture = processPaymentAsync(orderId);

        // 等待所有验证任务完成
        CompletableFuture<Void> allValidations = CompletableFuture.allOf(
                userValidationFuture, inventoryCheckFuture, paymentProcessingFuture
        );

        // 处理验证结果
        CompletableFuture<String> orderProcessingFuture = allValidations.thenCompose(v -> {
            // 检查是否有验证失败
            try {
                String userValidationResult = userValidationFuture.get();
                String inventoryCheckResult = inventoryCheckFuture.get();
                String paymentProcessingResult = paymentProcessingFuture.get();

                if (userValidationResult.contains("失败") ||
                        inventoryCheckResult.contains("失败") ||
                        paymentProcessingResult.contains("失败")) {

                    return CompletableFuture.completedFuture("订单验证失败，无法处理订单");
                }

                // 所有验证通过，处理订单
                return processOrderAsync(orderId);

            } catch (Exception e) {
                return CompletableFuture.completedFuture("订单处理异常: " + e.getMessage());
            }
        });

        // 处理最终结果
        orderProcessingFuture.thenAccept(result -> {
            long endTime = System.currentTimeMillis();
            System.out.println("订单处理结果: " + result);
            System.out.println("总耗时: " + (endTime - startTime) + "ms");
        }).exceptionally(ex -> {
            System.err.println("订单处理失败: " + ex.getMessage());
            return null;
        }).get(); // 等待异步操作完成

        executor.shutdown();
    }

    // 模拟用户验证
    private static CompletableFuture<String> validateUserAsync(String orderId) {
        return CompletableFuture.supplyAsync(() -> {
            System.out.println("开始用户验证: " + orderId);
            try {
                TimeUnit.MILLISECONDS.sleep(200);
                // 模拟90%的成功率
                if (Math.random() > 0.1) {
                    return "用户验证成功";
                } else {
                    return "用户验证失败";
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return "用户验证异常: " + e.getMessage();
            }
        }, executor);
    }

    // 模拟库存检查
    private static CompletableFuture<String> checkInventoryAsync(String orderId) {
        return CompletableFuture.supplyAsync(() -> {
            System.out.println("开始库存检查: " + orderId);
            try {
                TimeUnit.MILLISECONDS.sleep(300);
                // 模拟95%的成功率
                if (Math.random() > 0.05) {
                    return "库存检查成功";
                } else {
                    return "库存检查失败";
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return "库存检查异常: " + e.getMessage();
            }
        }, executor);
    }

    // 模拟支付处理
    private static CompletableFuture<String> processPaymentAsync(String orderId) {
        return CompletableFuture.supplyAsync(() -> {
            System.out.println("开始支付处理: " + orderId);
            try {
                TimeUnit.MILLISECONDS.sleep(500);
                // 模拟85%的成功率
                if (Math.random() > 0.15) {
                    return "支付处理成功";
                } else {
                    return "支付处理失败";
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return "支付处理异常: " + e.getMessage();
            }
        }, executor);
    }

    // 模拟订单处理
    private static CompletableFuture<String> processOrderAsync(String orderId) {
        return CompletableFuture.supplyAsync(() -> {
            System.out.println("开始处理订单: " + orderId);
            try {
                TimeUnit.MILLISECONDS.sleep(800);
                return "订单处理成功，订单号: " + orderId;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return "订单处理异常: " + e.getMessage();
            }
        }, executor);
    }
}
